package cn.edu.tju.core.security.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.edu.tju.core.security.SecurityUtils;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.repository.UserRepository;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserService {

   private final UserRepository userRepository;

   public UserService(UserRepository userRepository) {
      this.userRepository = userRepository;
   }

   @Transactional(readOnly = true)
   public Optional<User> getUserWithAuthorities() {
      return SecurityUtils.getCurrentUsername().flatMap(userRepository::findOneWithAuthoritiesByUsername);
   }

   @Transactional(readOnly = true)
   public Optional<User> getUserById(Long id) {
      return userRepository.findById(id);
   }

   public User addUser(User user) {
      return userRepository.save(user);
   }

   public User updateUser(User user) {
      return userRepository.save(user);
   }

   public Boolean isEmptyUserTable() {
      List<User> userList = userRepository.findAll();
      return userList.isEmpty();
   }

   @Transactional(readOnly = true)
   public Optional<User> getUserByUsername(String username) {
      return userRepository.findOneWithAuthoritiesByUsername(username);
   }

   public User createUser(User user) {
      return userRepository.save(user);
   }

   public User updateUserInfo(User user) {
      return userRepository.save(user);
   }

   public boolean changePassword(Long userId, String oldPassword, String newPassword) {
      Optional<User> userOpt = userRepository.findById(userId);
      if (userOpt.isPresent()) {
         User user = userOpt.get();
         // 这里需要验证旧密码，暂时简化处理
         user.setPassword(newPassword);
         userRepository.save(user);
         return true;
      }
      return false;
   }

   public boolean updateAvatar(Long userId, String avatarBase64) {
      Optional<User> userOpt = userRepository.findById(userId);
      if (userOpt.isPresent()) {
         User user = userOpt.get();
         user.setUserImg(avatarBase64);
         userRepository.save(user);
         return true;
      }
      return false;
   }
}
